package com.test.base.netty_upgrade.fixlength;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * description 使用定长格式处理解决粘包的半包
 * 对应的client为FixLengthClient
 * @author zken
 * @CreateDate 2024/11/20 17:38:11
 */
@Slf4j
public class FixLengthServer {

    void start() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // 设置定长编码处理器及其长度
                    ch.pipeline().addLast(new FixedLengthFrameDecoder(10));
                    ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                }
            });

            ChannelFuture future = bootstrap.bind(8080);
            log.debug("{} binding...", future.channel());
            future.sync();
            log.debug("{} bounded...", future.channel());
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace(System.err);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            log.debug("stopped");
        }
    }

    public static void main(String[] args) {
        new FixLengthServer().start();
    }
}
